﻿using System;
using System.Collections;
using com.yoozoo.gta.Extension;
using TMPro;
using UnityEngine;
using Yoozoo.UI.YGUI;

namespace Yoozoo.Gameplay.RTS
{
    /// <summary>
    /// 英雄头像
    /// </summary>
    public class ComCommander : MonoBehaviour
    {
        /// <summary>
        /// 表示阵营的边框
        /// </summary>
        public YImage frame;

        public YImage assembleFrame;
        public YImage battleLine;
        /// <summary>
        /// 英雄头像
        /// </summary>
        public YImage HeroIcon;
        /// <summary>
        /// 表示品质的背景
        /// </summary>
        public YImage QualityBG;

        /// <summary>
        /// 头像血条
        /// </summary>
        public YImage HpBar;

        /// <summary>
        /// 头像血条闪动
        /// </summary>
        public YImage HpBarFlash;

        public GameObject SkillFocusEffect;
        
        public GameObject[] deadEffect;
        private bool isActive;

        private int team;
        private bool isGather = false;
        private bool isScout = false;
        
        private MarchEntity entity;
        private Animation selectAnimation;
        private Animator releaseAnimator;
        private Animation shoujiEffectAnimation;
        private Animation hitAni;
//        private Animation subReleaseAni;
        private Animation changeHeadAni;
        private HudEffectPlayer releaseSkillEffect;
        private HudEffectPlayer skillHitEffect;
        private HudEffectPlayer releaseSkillNameEffect;
        private GameObject effectTrans;
        public int heroId;
        private int baseSkillEffectOrder = 5;
        private Transform rootTransform;

        private Coroutine _coroutine;
        private bool isGray = false;
        
        public Transform edge;
        private void Awake()
        {
            isActive = gameObject.activeSelf;
            selectAnimation = transform.Find("Root/SelectEffect/zong").GetComponent<Animation>();
            shoujiEffectAnimation = transform.Find("Root/shoujiEffectRoot").GetComponent<Animation>();
            //把技能选中框的默认alpha值设为0
            var renderer = selectAnimation.GetComponentsInChildren<SpriteRenderer>();
            if (renderer!=null)
            {
                for (int i = 0; i < renderer.Length; i++)
                {
                    var render = renderer[i];
                    MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
                    propertyBlock.Clear();
                    render.GetPropertyBlock(propertyBlock);
                    propertyBlock.SetFloat("_Alpha1", 0);
                    render.SetPropertyBlock(propertyBlock);
                }
            }

            rootTransform = transform.Find("Root");
//            subReleaseAni = rootTransform.GetComponent<Animation>();
            //effectTrans = transform.Find("Root/sfx_ui_rts_skill_1").gameObject;
        }

    

        public void InitAnimation(Animator releaseAnimator,Animation changeHeadAni)
        {
            this.releaseAnimator = releaseAnimator;
            this.changeHeadAni = changeHeadAni;
        }

        private string tempHeroIcon;
        public void SetHero(string heroIcon, bool isMainHero)
        {
            this.baseSkillEffectOrder = isMainHero ? 5 : 8;
            SetHeroIcon(heroIcon);
        }

        public void SetHeroIcon(string heroIcon)
        {
            if (string.IsNullOrEmpty(heroIcon))
            {
                return;
            }
            ArmyManager.Instance.ResourceManager.SetHeroIcon(heroIcon, HeroIcon);
        }
        private const string frm_rts_gray = "frm_rts_gray";
        private const string frm_rts_green = "frm_rts_green";
        private const string frm_rts_blue = "frm_rts_blue";
        private const string frm_rts_red = "frm_rts_red";
        private const string frm_rts_assembly = "frm_rts_assemble";
        private const string frm_rts_gray_blood = "frm_rts_gray_blood";
        private const string frm_rts_green_blood = "frm_rts_green_blood";
        private const string frm_rts_blue_blood = "frm_rts_blue_blood";
        private const string frm_rts_red_blood = "frm_rts_red_blood";
        
        public void SetTeam(int team,bool isGather = false,bool force = false,bool _isScout = false)
        {
            if (this.team != team || force)
            {
                this.team = team;
                if (isActive)
                {
                    string iconName;
                    string bloodName;
                    switch (team)
                    {
                        case 0:
                            iconName = frm_rts_green;
                            bloodName = frm_rts_green_blood;
                            break;
                        case 1:
                            iconName = frm_rts_blue;
                            bloodName = frm_rts_blue_blood;
                            break;
                        case 2:
                            iconName = frm_rts_red;
                            bloodName = frm_rts_red_blood;
                            break;
                        case 3:
                            iconName = frm_rts_gray;
                            bloodName = frm_rts_gray_blood;
                            break;
                        default:
                            iconName = frm_rts_gray;
                            bloodName = frm_rts_gray_blood;
                            break;
                    }
                    assembleFrame.enabled = isGather;
//                    frame.enabled = !isGather;

                    if (isGather)
                    {
                        this.isGather = true;
                        iconName = frm_rts_assembly;
                        ArmyManager.Instance.ResourceManager.SetHeadFrameIcon(iconName, assembleFrame);
                    }
                    else
                    {
                        this.isGather = false;
                        ArmyManager.Instance.ResourceManager.SetHeadFrameIcon(iconName, frame);
                    }
                    ArmyManager.Instance.ResourceManager.SetHeadFrameIcon(bloodName, HpBar);
                }
            }
            else
            {
                if (_isScout && !this.isScout)
                {
                    this.isScout = true;
                    this.isGather = false;
                    ArmyManager.Instance.ResourceManager.SetHeadFrameIcon(frm_rts_gray_blood, frame);
                    ArmyManager.Instance.ResourceManager.SetHeadFrameIcon(frm_rts_gray_blood, HpBar);
                }
            }
            
        }
        
        public void SetGatherFrame(bool isGather)
        {
            if (isGather && !this.isGather)
            {
                assembleFrame.enabled = true;
                this.isGather = true;
                ArmyManager.Instance.ResourceManager.SetHeadFrameIcon(frm_rts_assembly, assembleFrame);
            }

            if (!isGather && this.isGather)
            {
                assembleFrame.enabled = false;
                this.isGather = false;
                SetTeam(team,false,true);
            }
        }
        
        public void SetHpBarProgress(float progress,bool forceRefresh = false)
        {
            hpPercent = progress;
            UpdateHpBarProgress(forceRefresh);
        }
        
        public void UpdateHpBarProgress(bool forceRefresh)
        {
            var last = HpBar.fillAmount;
            if (hpPercent < last && !forceRefresh)
            {
                startFlashTime = Time.time;
                HpBarFlash.fillAmount = hpPercent;
            }
            HpBar.fillAmount = hpPercent;
        }
        

        public void SetActive(bool value, bool init = false)
        {
            if (isActive == value && !init)
                return;

            isActive = value;
            if (isActive)
            {
                frame.enabled = true;
                //Bg.enabled = true;
                HeroIcon.enabled = true;
            }
            else
            {

                frame.enabled = false;

                QualityBG.enabled = false;
                //Bg.enabled = false;
                HeroIcon.enabled = false;
            }
        }

        public bool GetActive()
        {
            return isActive;
        }


        public void ShowSkillFocusEffect()
        {
            if (SkillFocusEffect != null)
            {
                SkillFocusEffect.transform.localScale = Vector3.one;
            }
            bool playAnimation = selectAnimation.Play("ani_sfx_ui_country_1");
        }
        private static Vector3 releaseSkillOffSet = new Vector3(50.3f, 82.5f, 0);
        public void ShowReleaseSkillEffect(string skillName, Action onOver = null)
        { 
            this.releaseAnimator.SetTrigger("ani_sfx_ui_rts_skill_11");
            //this.skillNameCom.text = string.Empty;
            if (releaseSkillEffect != null)
            {
                releaseSkillEffect.Play();
            }
            else
            {
                releaseSkillEffect = new HudEffectPlayer(801, rootTransform, (o =>
                {
                    if (o != null)
                    {
                        o.transform.localPosition = releaseSkillOffSet;// - rootTransform.localPosition;
                        o.transform.localScale = new Vector3(1.1f,1.1f,1.1f);
                    }
                }), () =>
                {
                    RecoverReleaseSkillEffect();
                    onOver?.Invoke();
                }, 2.5f);
                releaseSkillEffect.SetChildIndex(3);
            }
        }

        /// <summary>
        /// 非主将第一顺位释放技能特效
        /// </summary>
        public void ShowReleaseSkillEffectNotMainCommander(Action onOver = null)
        {
            changeHeadAni.Play("ani_sfx_ui_rts_skill_change"); 
            if (releaseSkillEffect != null)
            {
                releaseSkillEffect.Play();
            }
            else
            {
                releaseSkillEffect = new HudEffectPlayer(801, transform, (o =>
                {
                    if (o != null)
                    {
                        o.transform.localPosition = Vector3.zero;
                        o.transform.localScale = Vector3.one;
                    }
                }), () =>
                {
                    RecoverReleaseSkillEffect();
                    onOver?.Invoke();
                }, 2.5f);
            }
        }

        private IEnumerator PlaySkillParticleEffect(Action onOver = null)
        {
            yield return new WaitForSeconds(0.2f);
            if (this.releaseSkillNameEffect == null)
            {
                this.releaseSkillNameEffect = new HudEffectPlayer(804, transform, (go) =>
                {
                    go.transform.localPosition = new Vector3(60.9f, 0, 0);
                    go.transform.localScale = Vector3.one;
                    /*var particles = go.GetComponentsInChildren<ParticleSystem>();
                    foreach (var particle in particles)
                    {
                        var render = particle.GetComponent<ParticleSystemRenderer>();
                        render.sortingOrder = baseSkillEffectOrder;
                    }*/
                }, () =>
                {
                    RecoverReleaseSkillEffect();
                    onOver?.Invoke();
                }, 2.2f);
            }
            else
                this.releaseSkillNameEffect.Play();
        }

        public void RecoverReleaseSkillEffect()
        {
            if (releaseSkillEffect != null)
            {
                releaseSkillEffect.Dispose();
                releaseSkillEffect = null;
            }

            if (this.releaseSkillNameEffect != null) 
            {
                this.releaseSkillNameEffect.Dispose();
                this.releaseSkillNameEffect = null;
            }
        }

        public void ShowSkillHitEffect()
        {
            if (shoujiEffectAnimation != null)
            {
                shoujiEffectAnimation.transform.localScale = Vector3.one;
                shoujiEffectAnimation.Play("ani_sfx_ui_rts_shouji");
            }
        }

        public void StopAnimation()
        {
//            var color = this.HeroIcon.color;
            //if (selectAnimation!=null)
            //{
            //    ResetAni(selectAnimation, "ani_sfx_ui_country_1");
            //}
//            this.HeroIcon.color = new Color(color.r, color.g, color.b, HeroIcon.color.a);
        }
        public void ResetAni(Animation ani, string name,float resetTime = 0)
        {
            if (ani == null)
            {
                return;
            }
            AnimationState state = ani[name];
            ani.Play(name);
            if (state == null)
            {
                return;
            }
            state.time = resetTime;
            ani.Sample();
            state.enabled = false;
        }
        public void RecoverSkillHitEffect() 
        {
            if (skillHitEffect !=null)
            {
                skillHitEffect.Dispose();
                skillHitEffect = null;
            }
        }

        public void Dispose(bool deleteHeadIcon)
        {
            RecoverReleaseSkillEffect();
            RecoverSkillHitEffect();
            if (SkillFocusEffect != null)
            {
                SkillFocusEffect.transform.localScale = Vector3.zero;
            }

            if (shoujiEffectAnimation!=null)
            {
                shoujiEffectAnimation.transform.localScale = Vector3.zero;
            }
            if (deleteHeadIcon)
            {
                HeroIcon.sprite = null;
            }
            if (deadEffect!=null)
            {
                foreach (var effect in deadEffect)
                {
                    if (effect.activeInHierarchy)
                    {
                        effect.SetActive(false);
                    }
                }
            }

            isScout = false;
            isGather = false;
            SetGray(false);
            if (assembleFrame)
            {
                if (assembleFrame.enabled)
                {
                    assembleFrame.enabled = false;
                }
            }
        }

        public void SetQuality(int quality)
        {
            string qualityPicName = $"frm_sendTroop_head_{quality}";
            ArmyManager.Instance.GetRtsResourceManager().SetHeroRtsAtlasIcon(qualityPicName,QualityBG);
        }

        public void SetGray(bool isGray)
        {
            if (isGray != this.isGray)
            {
                string path = isGray
                ? RTSResourceManager.MARCHHUD_SPRITE_GRAY_MAT
                : RTSResourceManager.MARCHHUD_SPRITE_MAT;


                if (frame.enabled)
                {
                    ArmyManager.Instance.ResourceManager.LoadMaterial(path, frame);
                }
                ArmyManager.Instance.ResourceManager.LoadMaterial(path, HeroIcon, () =>
                {
                    this.isGray = isGray;
                });
            }
        }
        internal void SetLod1Mat()
        {
            var images = gameObject.GetComponentsInChildren<YImage>(true);
            foreach (var image in images)
            {
                ArmyManager.Instance.ResourceManager.LoadMaterial(RTSResourceManager.MARCHHUD_LOD1_SPRITE_MAT, image);
            }
        }
        private void OnDisable()
        {
            Dispose(false);
        }

        private float hpPercent;
        private float startFlashTime = 0;
        private float flashDuration = 0.1f;
        private float flashFadeDuration = 0.1f;

        void Update()
        {
            if (HpBarFlash != null && HpBarFlash.Valid())
            {
                if (startFlashTime != 0)
                {
                    var endFlashTime = startFlashTime + flashDuration;
                    var endFadeTime = endFlashTime + flashFadeDuration;
                    if (Time.time > endFadeTime)
                    {
                        startFlashTime = 0;
                        HpBarFlash.color = new Color(1, 1, 1, 1);
                        HpBarFlash.fillAmount = 0;
                    }
                    else if (Time.time >= endFlashTime)
                    {
                        HpBarFlash.color = new Color(1, 1, 1, 1);//这段代码会有概率让头像黑掉(endFadeTime - Time.time) / flashDuration);
                        HpBarFlash.fillAmount = hpPercent;
                    }
                    else
                    {
                        HpBarFlash.color = new Color(1,1,1,1);
                        HpBarFlash.fillAmount = hpPercent;
                    }
                }
                else
                {
                    if(HpBarFlash.color.a != 1)
                    {
                        HpBarFlash.color = new Color(1, 1, 1, 1);
                    }
                }
            }
           
        }
    }
}
